<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/6
 * Time: 10:47
 */

namespace App\Http\Controllers\Api\V4;

use App\Common\ApiData;
use App\Models\V1\LiveModel;
use App\Modules\EntMemberDRP;
use Illuminate\Http\Request;
use Validator;

use App\Models\V2\BookSentenceModel;
use App\Models\V2\MemberModel;
use App\Models\V2\BookModel;
use App\Models\V2\ArticleModel;
use App\Models\V2\AudioModel;
use DB;


class HomeController extends BaseController
{
    protected $url;

    public function __construct()
    {
        $this->url = env('ADMIN_HOST');
    }


    /**
     * 首页接口
     *
     */
    public function getHomeList(Request $request)
    {
        $name = $request->input('mobile', '');
        $key  = $request->input('key', '');
        //直播信息
        $live_info   = LiveModel::where(['is_end' => 0, 'is_completed' => 1, 'is_show' => 1])
            ->select('live_title', 'description', 'id', 'live_type', 'begin_time', 'live_status')
            ->orderBy('id', 'desc')->first();
        $memberModel = new MemberModel();
        $memberInfo  = ($name && $key) ? $memberModel->get_member_info_by_mobile_key($name, $key) : false;
        $mstate      = ($memberInfo && $memberInfo->isValid) ? 1 : 0;

        if ($live_info) {//有直播

            if ($live_info->live_type == 1) {
                if ($memberInfo && $memberInfo->isValid) {//用户是有效的
                    $memnumber           = $memberInfo->MemNumber;
                    $level               = EntMemberDRP::where('MemNumber', $memnumber)->select('DRPLevel')->first();//判断用户是否是学习官
                    $live_info->is_watch = ($level && $level->DRPLevel == 1) ? 1 : 0;
                } else {//用户无效
                    $live_info->is_watch = 0;
                }
            } else {//用户不是学习官
                $live_info->is_watch = 1;
            }
            //判断是否正在直播
            $live_info->is_live_now = $live_info->live_status == 1 ? 1 : 0;
        }

        unset($live_info->live_status);

        /*每日一言*/
        $audioModel = new AudioModel();
        $audioList  = $audioModel->get_audio_list();

        foreach ($audioList as $audio) {
            $params = [
                'audioId'  => $audio->AudioID,
                'parentId' => 0
            ];
            $params = http_build_query($params);

            $shareInfo        = [
                'title'       => "老侯论道",
                'groupTitle'  => $audio->AudioTitle,
                'description' => $audio->AudioTitle,
                'img'         => env('ADMIN_HOST') . "/images/default-images/share-mp3.png",
                'link'        => env('ADMIN_HOST') . "/home/audio_share_to_weixin?" . $params,
                "audio"       => $audio->FilePath1,
            ];
            $audio->shareInfo = $shareInfo;
        }


        /*热门书籍*/
        $bookModel = new BookModel();
        $hotBooks  = $bookModel->get_hot_books();

        /*心灵分享*/
        $articleModel = new ArticleModel();
        $articles     = $articleModel->get_articles(5);


        $bookSentenceModel    = new BookSentenceModel();
        $date                 = current_date();
        $bookSentence         = $bookSentenceModel->get_day_sentence($date);
        $bookSentence->bg_img = env('HOST') . "/" . $bookSentence->bg_img;

        //$guozhengFaceImg    = env('HOST') . system_log('gz_face_img');
        $guozhengFaceImg = "";
        $loginBgImg      = env('HOST') . system_log('login_bg_img');//登录背景图片

        return apiData()->set_data('mstate', $mstate)
            ->set_data('guozhengFaceImg', $guozhengFaceImg)
            ->set_data('loginBgImg', $loginBgImg)
            ->set_data('dayslist', $audioList)
            ->set_data('hotslist', $hotBooks)
            ->set_data('liveInfo', $live_info)
            ->set_data('mindsharelist', $articles)
            ->set_data('bookSentence', $bookSentence)
            ->send('200', 'ok');
    }

    /**
     * 音频分页
     * */
    public function page_audio(Request $request)
    {
        $perNumber  = $request->input('perPage', 20);
        $audioModel = new AudioModel();
        $audioList  = $audioModel->get_audio_list($perNumber);

        foreach ($audioList as $audio) {
            $params = [
                'audioId'  => $audio->AudioID,
                'parentId' => 0
            ];
            $params = http_build_query($params);

            $shareInfo        = [
                'title'       => "老侯论道",
                'groupTitle'  => $audio->AudioTitle,
                'description' => $audio->AudioTitle,
                'img'         => env('ADMIN_HOST') . "/images/default-images/share-mp3.png",
                'link'        => env('ADMIN_HOST') . "/home/audio_share_to_weixin?" . $params,
                "audio"       => $audio->FilePath1,
            ];
            $audio->shareInfo = $shareInfo;
        }

        $apiData = new ApiData();

        return $apiData->set_data('data', $audioList)->send_old(200, 'ok');
    }


    /**
     * 每天的音频
     * */
    public function audio_list(Request $request)
    {

        $name   = $request->input('mobile', '');
        $key    = $request->input('key', '');
        $oldKey = $request->input('oldKey', '');

        if ($oldKey && $key && $oldKey != $key) {
            $db = DB::table('memberinfo')
                ->where('AppKey', $oldKey)
                ->where('DeleteMark', 1);
            //检查新的key是否存在 存在表示已经更新
            if ($name) { //两个key都存在 并且不相等 把旧的key改为新的key
                $db->where('UserName', $name);
            }
            $db->update(['Appkey' => $key]);
        }

        /*每日一言*/
        $audioModel = new AudioModel();
        $audioList  = $audioModel->get_audio_all();

        foreach ($audioList as $audio) {

            $params = [
                'audioId'  => $audio->AudioID,
                'parentId' => 0
            ];
            $params = http_build_query($params);

            $shareInfo        = [
                'title'       => "老侯论道",
                'groupTitle'  => $audio->AudioTitle,
                'description' => $audio->AudioTitle,
                'img'         => env('ADMIN_HOST') . "/images/default-images/share-mp3.png",
                'link'        => env('ADMIN_HOST') . "/home/audio_share_to_weixin?" . $params,
                "audio"       => $audio->FilePath1,

            ];
            $audio->shareInfo = $shareInfo;
        }

        $data = [
            'message' => 'ok',
            'code'    => '200',
            'data'    => ['dayslist' => $audioList],
        ];

        return response()->json($data);
    }


    /**
     * 获得文章列表
     * */
    public function get_articles()
    {
        /*心灵分享*/
        $articleModel = new ArticleModel();
        $articles     = $articleModel->get_articles(5);
        $apiData      = new ApiData();

        return $apiData->set_data('data', $articles)->send_old(200, 'ok');
    }


    /**
     * 媒体播放日志
     * */
    public function media_play_log(Request $request)
    {
        $medias      = $request->input('medias');
        $medias      = \GuzzleHttp\json_decode($medias);
        $userId      = $request->input('userId');
        $time        = date_time();
        $memberModel = new MemberModel();

        $types = [
            "lhddmp4" => "看老侯代读视频",
            "lhddmp3" => "听老侯代读音频",
            "gzsbmp4" => "看国政书吧视频"
        ];

        foreach ($medias as $media) {
            $data = [
                'media_id'   => $media->media_id,
                'media_type' => $media->media_type,
                'user_id'    => $userId,
                'begin_time' => date_time($media->begin_time),
                'end_time'   => date_time($media->end_time),
                'created_at' => $time,
                'updated_at' => $time
            ];
            DB::table('media_play_log')->insert($data);

            //计算积分  每看视频10分钟加三分
            $minute     = round(($media->end_time - $media->begin_time) / 60);
            $tenMinutes = $minute / 1;
            $integral   = $tenMinutes * 1;
            $note       = $types[$media->media_type] . $minute . "分钟";
            $memberModel->add_member_integral($userId, $integral, $media->media_id, $note);
        }

        return apiData()->send(200, 'ok');
    }


    /**
     * 记录微信分享日志
     * */
    public function wx_share_log(Request $request)
    {
        $shareContent = [
            'index1' => [5, '老侯论道分享'],
            'index2' => [5, '言图分享'],
            'index3' => [5, '自学习社群文章'],
            'index4' => [5, '自己的读书改进计划'],
            'index5' => [5, '听代读签到']
        ];

        $index     = "index" . $request->input('contentType');
        $info      = $shareContent[$index];
        $userId    = $request->input('userId');
        $contentId = $request->input('contentId');
        $integral  = $info[0];
        $note      = $info[1];

        $memberModel = new MemberModel();
        $memberModel->add_member_integral($userId, $integral, $contentId, $note);

        return apiData()->send(200, 'ok');
    }


}